#include "stdafx.h"
#include "gamemanager.h"
#include "map/MapManager.h"
#include "inputmanager.h"
#include "ScriptSystem.h"

//#include "dxut/DXUT.h"
//#include "dxut/DXUTgui.h"
//#include "dxut/DXUTguiIME.h"
//#include "ui.h"
#include "Scene.h"
#include "TextureRender.h"
#include "TextureRender2.h"
#include "terrain.h"
#include "ObjectManager.h"
#include "config.h"
#include "Army.h"
#include "City.h"
#include "gamestate.h"
#include "world.h"

GlobalContext gc;

void GlobalContext::Reset()
{
    fscale = 1.0f;
    slidex = 1.0f;
    slidey = 1.0f;
    gridsize = 16;
}

CGameManager::CGameManager()
{
    m_curstate = NULL;
}

CGameManager::~CGameManager()
{

}

bool CGameManager::Update( uint32 delta )
{
    m_curstate->RunOneFrame( delta );
    return true;
}

void CGameManager::OnExit( int exitcode )
{
	//CMapManager::Instance().SaveMapData();
}

void CGameManager::Initialize()
{
    g_log.Initialize();

    CMapManager::Instance().LoadMapData();
    CInputManager::Instance().Initialize();
	//UI::Instance().Init();
    CTerrain::Instance().SetDimension( 1 + gc.mapregion.Width()/gc.gridsize, 1 + gc.mapregion.Height()/gc.gridsize, true );
    CTerrain::Instance().Load();

    Script.ExposeCppToLua();
    Script.DoFile( "config.lua");
    Script.DoFile("data\\Animation\\Animation.lua");
    //Script.DoFile("data\\UI\\UIManager.lua");
    //Script.CallLuaFunc<void>("InitUI");
    Config::Instance().ReadConfigs();
    sgWorld::Instance().Initialize();
    if( gc.gamestate == eGame_Editor )
        CTerrain::Instance().SaveTerrainTileToFile( L"\\data\\TerrainIcon\\" );

    gc.fscale = 4.0f;

    //sgArmy *army = new sgArmy(2);
    //army->Initialize();
    //army->SetPosition( IPoint(100,100) );
    //CObjectManager::Instance().AddObject( army );

    sgCity *city = new sgCity(1);
    city->Initialize();
    city->SetPosition( IPoint(200,100) );
    CObjectManager::Instance().AddObject( city );

    g_log.WriteInfo( "GameManager Initialize Finish..." );
}

void CGameManager::ExitGame( int exitcode )
{
	OnExit(exitcode);
	PostQuitMessage(exitcode);
}

void CGameManager::SwitchState( IGameState *state )
{
    if( m_curstate )
    {
        m_curstate->ExitState();
    }
    m_curstate = state;
    m_curstate->EnterState();
}
